"""
关注加油站
"""
import os
import sys
import django
import datetime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(BASE_DIR)
sys.path.insert(0, BASE_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'finance_c2c.settings'
django.setup()

from core.zhongxin.client import ZXClient
from apps.czb.models import Orders
from core.zhongxin.models import OrderRecord

zx_client = ZXClient()


def verify_with_rsa():
    msgBody = {'amount': "15542", 'originSerialNo': '21052816483971230541', 'amtType': '156', 'tranSerialNo': '614229',
               'retMsg': '交易成功', 'originTranTime': '2021-05-28 16:48:39', 'serialNo': '210528164900955186074208',
               'originMerId': '242020071400054', 'trxTime': '2021-05-28 16:49:00', 'tranResult': 'TRADE_SUCCESS',
               'payCode': 'KLB'}
    msgSignature = 'BXm1b4wPMh2cdrFEFp0R3cDflTAY3vxYI8lxzpJDhrw/uQhTBEgxdE7aEwcI+aKPuWFzNEW7d9ozuSCIHqiHdC5ucowssMZD4hqg9pG9kI7/exHkGujnpLpaw6IEelbfhPge5JkCzVrKtsHRnfT+Xh0955mJ3jm0HA9JK6IxFOGfKLTOD13L+PZQvq5WaEb+bZiKeX7QBPywNYGTnrSB05lyYjgy8JBGTVpMuXSzl0lidcmo6mvK/x7pyAfHPIZBtjLAFfryjoV8iUPqAXteXRyCGEO/sboXJJeDoVPa1GBDuQWu68S+GFvhdEBxlexp2bP0q5ZvZ4IH6MGA3lGOKg=='
    result = zx_client.verify_with_rsa(msgBody, msgSignature)
    print(result)


def deal_with_orders(orders, print_day):
    if "|0327|" in orders:
        msg = "已退款"
        cash = orders.split("|0327|")[-1].split("|")[0]
    else:
        cash = orders.split("|0325|")[-1].split("|")[0]
        msg = "支付订单"
    zx_out_trade_no = orders.split("||")[0].split("|")[-1]
    try:
        Orders.objects.get(out_trade_no=zx_out_trade_no, result=1, pay_type=6)
    except Exception as e:
        print(print_day.date(), zx_out_trade_no, cash, msg)


def orders_download():
    format_date = "20210530"
    orders_day = datetime.datetime.strptime(format_date, "%Y%m%d")
    print_day = orders_day - datetime.timedelta(days=1)

    params, response = ZXClient().download_order(format_date)
    msgAnnex = response.get("msgAnnex")
    record = msgAnnex.get("record")
    for i in record:
        orders = i.get("record").replace(" ", "")
        print(orders)
        # deal_with_orders(orders, print_day)


def refund_cash(out_trade_no):
    zx_order_record = OrderRecord.objects.filter(out_trade_no=out_trade_no).order_by("id").last()
    oldOriginSerialNo = zx_order_record.out_trade_no
    oldOriginTranTime = zx_order_record.requestTimestamp.strftime("%Y-%m-%d %H:%M:%S")
    installment = zx_order_record.installment
    cashAmount = str(zx_order_record.totalAmount)
    params, response = zx_client.refund_order(oldOriginSerialNo, oldOriginTranTime, cashAmount, installment)
if __name__ == '__main__':
    refund_cash("21052914585732489975")
    # orders_download()